﻿using System.ComponentModel;

namespace sinetd.Services.Tee
{
    public class Service : BaseService, IService
    {
        public Service()
            : base("Tee")
        {
        }

        IConnectionIO connA;
        IConnectionIO connB;

        BackgroundWorker bw;

        #region IService Members

        string id = "TeeConn";

        public void HandleNewConnection(IConnectionIO conn)
        {
            try
            {
                connB = (IConnectionIO)Protocols.Manager.GetOrCreate("Tcp", id);
                id = ((Protocols.IProtocol)connB).Id;
                ((Protocols.IProtocol)connB).Close();
            }
            catch { }

            connA = conn;

            if (connB != null)
            {
                if (((Protocols.IProtocol)connB).Connect())
                {
                    string msg = "";
                    msg = connA.Recv();

                    if (msg != null)
                    {
                        System.IO.File.AppendAllText("tee.txt", msg + "\r\n");

                        connB.Send(msg);

                        bw = new BackgroundWorker();
                        bw.WorkerSupportsCancellation = true;
                        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                        bw.RunWorkerAsync();
                    }
                }
            }
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            string msg = "";
            //while (!bw.CancellationPending)
            {
                msg = connB.Recv();
                if (msg != null)
                {
                    System.IO.File.AppendAllText("tee.txt", msg + "\r\n");
                    connA.Send(msg);
                }
            }
        }

        public void Shutdown()
        {
            if (bw != null)
            {
                if (bw.IsBusy) bw.CancelAsync();
            }
        }

        #endregion
    }
}
